package com.app.controller.backstage;

import com.app.model.AdminUserModel;
import com.app.model.BannerModel;
import com.app.service.AdminUserService;
import com.app.service.BannerService;
import com.app.util.Result;
import com.app.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RestController
@RequestMapping("/admin")
public class AdminBannerController {
    @Autowired
    private BannerService bannerService;
    @Autowired
    private AdminUserService adminUserService;

    //增加和编辑
    @PostMapping("/insertAndUpdateBanner")
    public Result<Object> selectAndUpdateBanner(@RequestBody BannerModel banner, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");

        }
        if (banner.getId() == 0) {
            bannerService.insert(banner);
        }
        bannerService.updateById(banner);
        return Result.success("操作成功");
    }

    //删除
    @GetMapping("/deleteBannerById")
    public Result<Object> deleteBannerById(Integer id,
                                           HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (id != null && id != 0) {
            bannerService.deleteBannerById(id);
        }
        return Result.success("删除成功");
    }

    //查询轮播图列表
    @GetMapping("/selectBannerList")
    public Result<Object> selectBannerList(Integer page, Integer limit, String name) {
        return Result.success(bannerService.selectBannerList(page, limit, name));
    }

    //更新状态
    @GetMapping("/updateBannerStatus")
    public Result<Object> updateStatus(Integer id, Integer status, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        bannerService.updateStatus(id, status);
        return Result.success("更新成功");
    }
}
